/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package reprortes;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

/**
 *
 * @author w
 */
public class Reporte implements Serializable{

    HashMap<Integer, Integer>  map= new HashMap<Integer,Integer>();
    String  file;


    private Reporte(String file){
        this.file=file;
    }

    public static Reporte load(String file) throws IOException {
        Reporte r=new  Reporte(file);
            File f=new File(file);
            if(f.exists()){
            FileInputStream fileIn =
                          new FileInputStream(file);
            ObjectInputStream in = new ObjectInputStream(fileIn);
            try{
            r = (Reporte) in.readObject();
            }catch(ClassNotFoundException e){
                f.delete();
            }
            in.close();
            fileIn.close();
            }
            return r;
    }


    public List<Integer> getFirst(int n){
        List<Integer> list= new LinkedList<Integer>(map.keySet());

        Collections.sort(list,new Comparator(){

            public int compare(Object o1, Object o2) {
                return map.get(o2).compareTo(map.get(o1));
            }

        });
        if(list.size()<n){
            return list.subList(0, list.size());
        }
        return list.subList(0, n);
    }

    public void increment(int id){
        Integer cant=map.get(id);
        if(cant == null)
            map.put(id, 1);
        else
            map.put(id,cant+1);
        save();
    }

    private void save(){
                      try
      {
         FileOutputStream fileOut =
         new FileOutputStream(file);
         ObjectOutputStream out =
                            new ObjectOutputStream(fileOut);
         out.writeObject(this);
         out.close();
          fileOut.close();
      }catch(IOException i)
      {
          
      }
    }

    public int times(int id){
        return map.get(id);
    }

}
